package org.jetlinks.pro.rule.engine.service;

import lombok.AllArgsConstructor;
import org.hswebframework.web.api.crud.entity.PagerResult;
import org.hswebframework.web.api.crud.entity.QueryParamEntity;
import org.jetlinks.pro.rule.engine.device.SceneRule;
import org.jetlinks.pro.rule.engine.entity.RuleInstanceEntity;
import org.jetlinks.pro.rule.engine.web.response.SceneRuleInfo;
import org.jetlinks.rule.engine.api.RuleData;
import org.jetlinks.rule.engine.api.RuleEngine;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Map;

@Service
@AllArgsConstructor
public class SceneRuleService {
    private final RuleInstanceService instanceService;

    private final RuleEngine ruleEngine;

    public Mono<Void> execute(String id, Map<String, Object> data) {
        return ruleEngine
            .getTasks(id)
            .filter(task -> task.getJob().getNodeId().equals(id))
            .next()//只执行一个
            .flatMap(task -> task.execute(RuleData.create(data)))
            .then();
    }

    public Mono<PagerResult<SceneRuleInfo>> queryScene(QueryParamEntity query) {

        return query
            .toQuery()
            .where(RuleInstanceEntity::getModelType, SceneRule.modelType)
            .execute(param -> instanceService.queryPager(query, SceneRuleInfo::of));
    }

    public Flux<SceneRuleInfo> querySceneNoPaging(QueryParamEntity query) {
        return query
            .toQuery()
            .where(RuleInstanceEntity::getModelType, SceneRule.modelType)
            .execute(instanceService::query)
            .map(SceneRuleInfo::of);
    }

}
